<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Admin\Controller;
use think\Controller;
use Admin\Service\ScoreService;
use Admin\Service\ImageScoreService;
use Admin\Service\TagScoreService;
use Admin\Service\SheetService;
use Admin\Service\ScoreSheetService;
use Think\Page;

/**
 * 谱单控制器
 * @author Administrator
 *
 */
class ScoreController extends AdminController {

    public function index($order = 'id', $sort = 1)
    {
        if ($sort == 2) {
            $orderSort = $order.' desc';
        } else {
            $orderSort = $order;
        }
        $keywords = explode(' ', I('name'));
        foreach ($keywords as $key => $keyword) {
            $keywordArr[] = array('like', '%'.$keyword.'%');
        }
        $model = M('Score');
        $map = array(
            'name' => $keywordArr,
            'is_delete' => 0
        );
        /*$list   = $this->lists('Score', $map);*/
        //重写分页
        $count = count($model->where($map)->select());
        $listRows = 15;
        $page = new Page($count, $listRows);
        if($count>$listRows){
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p =$page->show();

        $list = $model->where($map)->limit($page->firstRow.','.$page->listRows)->order($orderSort)->select();
        $service = new ScoreService();
        /*//获取曲谱数量、评论数、收藏数、点击数、分享数
        $list = $service->getScoreCount($list);*/

        //获取谱单用户、标签信息
        $list = $service->convertList($list, $order, $sort);
        $this->assign('_page', $p? $p: '');
        $this->assign('_total',$count);

        $this->assign('_list', $list);
        $this->assign('_condition', I('post.'));
        $this->meta_title = '谱单信息';
        $this->display();
    }
    
    /**
     * 保存谱单
     */
    public function add(){

        if(IS_POST){
            $service = new ScoreService();
            try{
                $id = $service->add();
                $this->success('新增成功', U('Admin/Score/index'));
            } catch(\Exception $e){
                $this->error($e->getMessage());
            }
        } else {
            $this->meta_title = '新建谱单';
            $this->display();
        }
        
    }
    
    /**
     * 给谱单添加歌曲
     */
    public function sheet_add($method='', $score_id = 0){
    
        if($method == 'add'){
            $sheet_id = array_unique((array)I('id',0));
            if (empty($sheet_id)) {
                $this->error('请选择要操作的数据!');
            }

            $service = new ScoreSheetService();
            try{
                $id = $service->sheetAdd($score_id, $sheet_id);

                $this->success('新增成功');
            } catch(\Exception $e){
                $this->error($e->getMessage());
            }
        } else {
            $keywords = explode(' ', I('name'));
            foreach ($keywords as $key => $keyword) {
                $keywordArr[] = array('like', '%'.$keyword.'%');
            }
            $map = array(
                'name' => $keywordArr,
                'is_delete' => 0
            );
            if ($score_id == 0) {
                $score_id = I('score_id');
            }

            $list   = $this->lists('Sheet', $map);
            
            $service = new SheetService();
            $list = $service->convertList($list);

            //获取谱单内的曲谱id
            $model = M('ScoreSheet');
            $cond = array(
                'score_id' => $score_id,
                'is_delete' => 0
            );
            $sheetList = $model->where($cond)->field('sheet_id')->select();
            $sheetIds = array_column($sheetList, 'sheet_id');

            $this->assign('_list', $list);
            $this->assign('_condition', I('post.'));
            $this->assign('_scoreId', $score_id);
            $this->assign('sheetIds', $sheetIds);
            $this->meta_title = '添加曲谱';
            $this->display();
        }

    }
    
    /**
     * 给谱单添加歌曲
     */
    public function sheet_list( $score_id = 0){
        
        
        $name       =   I('name');
        $map['name'] = array('like', $name.'%');

        $list   = $this->lists('Sheet', $map);

        $service = new SheetService();
        $list = $service->convertList($list);
        $this->assign('_list', $list);
        $this->assign('_condition', I('post.'));
        $this->assign('_score_id', I('id'));
        print_r(I('id'));
        $this->meta_title = '添加曲谱';
        $this->display();
    
    }
    
    public function edit($id = 0){
    
        if(IS_POST){
            $service = new ScoreService();
            try{
                $id = $service->edit();
                $this->success('编辑成功', U('Admin/Score/index'));
            } catch(\Exception $e){
                $this->error($e->getMessage());
            }
        } else {
            if($id == 0) {
                $this->error('无效的参数');
            }
    
            $data = M('Score')->find($id);
            if(false === $data){
                $this->error("获取谱单信息错误");
            }
    
            //补全标签数据
            $sheetIdList = array($id);
            $tagScoreService = new TagScoreService();
            $tagMap = $tagScoreService->getTagsByScoreIds($sheetIdList);
            $data['tags'] = $tagMap[$id];
    
            $this->assign('data',$data);
            $this->meta_title = '编辑谱单';
            $this->display();
        }
    
    }
    
    public function getImages($score_id = 0 ){
        $cond = array(
            'score_id' => $score_id,
            'is_delete' => 0
        );
        $imgSheet = M('ImageScore')->where($cond)->select();
        $img_ids = array_column($imgSheet, "image_id");
    
        $map = array(
            'id' => array('in', $img_ids),
            'is_delete' => 0
        );
        $images = M('Image')->where($map)->select();
        $initialPreview = array_column($images, "url");
    
        $initialPreviewConfig = array();
        foreach ($images as $key => $image) {
            $initialPreviewConfig[$key] = array(
                "caption"   => $image['name'],
                "size"      => $image['size'],
                "url"       => "index.php?s=Admin/Score/removeImage/score_id/".$score_id."/image_id/".$image['id'],
                "key"       => $image['id'],
            );
        }

        $data = array(
            "initialPreview"=>$initialPreview,
            "initialPreviewConfig"=>$initialPreviewConfig
        );
        $this->success($data);
    }
    
    public function removeImage($score_id = 0 , $image_id){
        $service = new ImageScoreService();
        $rowCount = $service->delete($image_id, $score_id);
        $this->success($image_id);
    }

    /**
     * 删除谱单
     */
    public function del(){
    
        $id = array_unique((array)I('id',0));
    
        $id = is_array($id) ? implode(',',$id) : $id;
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        $map = array('id' => array('in', $id) );
        
        $Model = M('Score');
        $data = array(
            'is_delete' => 1
        );
        $Model->startTrans();
        $res = $Model->where($map)->save($data);
        //同时删除专区中的谱单
        $map2 = array(
            'score_id' => array('in', $id)
        );
        $hot = M('ScoreHot')->where($map2)->select();
        if ($hot) {
            $delHot = M('ScoreHot')->where($map2)->save($data);
        } else {
            $delHot = true;
        }
        $free = M('ScoreFree')->where($map2)->select();
        if ($free) {
            $delFree = M('ScoreFree')->where($map2)->save($data);
        } else {
            $delFree = true;
        }
        $new = M('ScoreNew')->where($map2)->select();
        if ($new) {
            $delNew = M('ScoreNew')->where($map2)->save($data);
        } else {
            $delNew = true;
        }
        //删除谱单和图片的关系
        M('ImageScore')->where($map2)->save($data);


        if ($res && $delHot && $delFree && $delNew) {
            $Model->commit();
            $this->success('删除成功');
        } else {
            $Model->rollback();
            echo $Model->getLastSql();
            $this->error('删除失败！');
        }
    }
    /**
     * 获取专区谱单
     * @param $model
     * @param string $order
     * @param int $sort
     */
    public function scoreZone($model, $order = 'id', $sort = 1)
    {
        $model = I('model');
        if ($model == 'ScoreFree') {
            $title = '免费专区谱单';
        } elseif ($model == 'ScoreHot') {
            $title = '最热专区谱单';
        } elseif ($model == 'ScoreNew') {
            $title = '最新专区谱单';
        }
        $keywords = explode(' ', I('name'));
        foreach ($keywords as $key => $keyword) {
            $keywordArr[] = array('like', '%' . $keyword . '%');
        }
        $map = array(
            'name' => $keywordArr
        );
        //获取分页数据
        $Model = M($model.' sh' );
        $list = $this->scoreZonePage( $Model, $map, 's.'.$order, $sort );

        $service = new ScoreService();
        //获取谱单用户、标签信息
        $list = $service->convertList( $list, $order, $sort );

        $this->assign( '_list', $list );
        $this->assign( '_condition', I( 'post.' ) );
        $this->assign( '_model', $model );
        $this->meta_title = $title;
        $this->display('scorezone');
    }

    /**
     * 设置专区置顶
     */
    public function setTop()
    {
        $model = I('model');
        $isTop = I('status');
        $id = I('id');
        if(empty($id)){
            return false;
        }
        $service = new ScoreService();
        $res= $service->setZoneTop($model, $id, $isTop);
        if($res==false){
            $this->error('操作失败');
        } else {
            $this->success('操作成功');
        }
    }

    /**
     * 添加专区谱单
     */
    public function addScoreToZone($method='', $model='')
    {
        if($method == 'add'){
            $scoreId = array_unique((array)I('id',0));

            if (empty($scoreId)) {
                $this->error('请选择要操作的数据!');
            }
            $service = new ScoreService();
            try{
                $id = $service->addScoreToZone($scoreId, $model);
                $this->success('新增成功');
            } catch(\Exception $e){
                $this->error($e->getMessage());
            }
        } else {
            $keywords = explode(' ', I('name'));
            foreach ($keywords as $key => $keyword) {
                $keywordArr[] = array('like', '%'.$keyword.'%');
            }

            $map = array(
                'name' => $keywordArr,
                'is_delete' => 0
            );
            //获取专区内已有谱单
            $cond = array(
                'is_delete'=>0,
            );
            $scorelist = M($model)->field('score_id')->where($cond)->select();
            $scoreIds = array_column($scorelist, 'score_id');

            $list = $this->lists('Score', $map);

            $service = new ScoreService();
            $list = $service->convertList($list);
            $this->assign('_list', $list);
            $this->assign('_condition', I('post.'));
            $this->assign('_model', I('model'));
            $this->assign('scoreIds', $scoreIds);
            $this->meta_title = '谱单信息';
            $this->display('score_add');
        }
    }

    /**
     * 删除专区谱单信息
     */
    public function delFromScoreZone($model='')
    {
        $id = array_unique((array)I('id',0));

        $id = is_array($id) ? implode(',',$id) : $id;
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }

        $map = array(
            'score_id' => array('in', $id)
        );

        $Model = M($model);
        $data = array(
            'is_delete' => 1
        );
        $res = $Model->where($map)->save($data);
        if ($res) {
            $this->success('删除成功');
        } else {
            echo $Model->getLastSql();
            $this->error('删除失败！');
        }
    }

    /**
     * 专区分页
     * @param $model
     * @param $map
     * @param string $order
     * @param int $sort
     * @return mixed
     */
    public function scoreZonePage($model, $map, $order = 's.id', $sort = 1)
    {
        if ($sort == 2) {
            $orderSort = $order.' desc';
        } else {
            $orderSort = $order;
        }
        $join = 'score s ON sh.score_id=s.id AND sh.is_delete=0 AND s.is_delete=0';
        //分页样式
        $query = $model->field('sh.score_id, count(*)')->join($join)->where($map)
            ->group('score_id')->select();
        $count = $query[0]['count(*)'];
        $listRows = 15;
        $page = new Page($count, $listRows);
        if($count>$listRows){
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p =$page->show();

        $list = $model->field('sh.score_id, sh.is_top, s.name, s.author_type, s.creator, s.create_time, s.is_private, sh.is_delete, s.comment_count, s.fav_count, s.sheet_count,s.click_count, s.share_count')
            ->join($join)->where($map)
            ->group('score_id')->order('is_top desc, score_id asc')
            ->limit($page->firstRow.','.$page->listRows)->order($orderSort)->select();

        $this->assign('_page', $p? $p: '');
        $this->assign('_total',$count);
        return $list;
    }

    public function count()
    {
        $model = M("score");
        $map = array(
            'is_delete' => 0
        );
        $list = $model->where($map)->field('id')->select();
        $service = new ScoreService();
        //获取曲谱数量、评论数、收藏数、点击数、分享数
        $list = $service->getScoreCount($list);
        foreach ($list as $score) {
            $model->where(array('id'=>$score['id']))->save($score);
        }
        $this->success('刷新成功');
    }


}
